package cn.bincker.mycaptcha.slider;

import cn.bincker.mycaptcha.basic.AnswerStorage;
import cn.bincker.mycaptcha.CaptchaVerifier;
import cn.bincker.mycaptcha.VerifyRequestAnswerResolver;
import cn.bincker.mycaptcha.slider.entity.SliderAnswer;
import cn.bincker.mycaptcha.basic.exception.CaptchaExpireException;
import cn.bincker.mycaptcha.basic.exception.CaptchaVerifyFailException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SliderCaptchaVerifier implements CaptchaVerifier {
    private final VerifyRequestAnswerResolver<SliderAnswer> answerResolver;
    private final AnswerStorage<SliderAnswer> answerStorage;
    private final SliderCaptchaProperties properties;

    public SliderCaptchaVerifier(VerifyRequestAnswerResolver<SliderAnswer> answerResolver, AnswerStorage<SliderAnswer> answerStorage, SliderCaptchaProperties properties) {
        this.answerResolver = answerResolver;
        this.answerStorage = answerStorage;
        this.properties = properties;
    }

    @Override
    public void verify(HttpServletRequest request, HttpServletResponse response) {
        var answer = answerResolver.resolver(request);
        var rightAnswer = answerStorage.getAndRemove(request).orElseThrow(CaptchaExpireException::new);
        if (Math.abs(answer.getX() - rightAnswer.getX()) > properties.getFaultToleranceValue()) {
            throw new CaptchaVerifyFailException();
        }
    }
}
